﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yoze.Common;
using Yoze.Common.Messaging;
using Yoze.Redis.Common;

namespace Yoze.Messaging.RedisMq
{
    /// <summary>
    /// 消息发布者
    /// </summary>
    public abstract class RedisMqMessagePublisher : DisposableObject, IMessagePublisher
    {
        private readonly string exchangeName;
        private readonly string url;
        //private readonly IConnection connection;
        //private readonly IModel channel;
        private bool disposed;
        private RedisService redis;

        protected RedisMqMessagePublisher(string uri, string exchangeName)
        {
            this.exchangeName = exchangeName;
            this.url = uri;
            redis = new RedisService(url);
            //var factory = new ConnectionFactory() { Uri = uri };
            //this.connection = factory.CreateConnection();
            //this.channel = connection.CreateModel();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!disposed)
                {
                    //this.channel.Dispose();
                    //this.connection.Dispose();
                    disposed = true;
                }
            }
        }

        /// <summary>
        /// 发布消息 
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="message"></param>
        public void Publish<TMessage>(TMessage message)
        {
            //channel.ExchangeDeclare(exchange: this.exchangeName, type: "fanout");

            var json = JsonConvert.SerializeObject(message, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
            //var bytes = Encoding.UTF8.GetBytes(json);

            //System.Diagnostics.Trace.WriteLine($"RedisMq published: {json}");

            //channel.BasicPublish(exchange: this.exchangeName, routingKey: "", basicProperties: null, body: bytes);

            redis.PublishMessage(this.exchangeName, json);

            System.Diagnostics.Trace.WriteLine($"RedisMq Publish msg:{json}");
        }
    }
}
